from flask import Blueprint, request, jsonify
from datetime import datetime

# 创建蓝图
business_bp = Blueprint('business', __name__)

# 模拟数据存储（实际项目中应该使用数据库）
products_data = [
    {
        'id': 1,
        'productNumber': 'P001',
        'productName': '苹果手机',
        'productModel': 'iPhone 15',
        'category': '电子产品',
        'unit': '台',
        'price': 5999.0,
        'stock': 100,
        'material': '玻璃',
        'brand': '苹果',
        'color': '深空灰',
        'status': '正常',
        'created_at': '2025-10-20 10:00:00'
    },
    {
        'id': 2,
        'productNumber': 'P002',
        'productName': '华为笔记本',
        'productModel': 'MateBook X Pro',
        'category': '电子产品',
        'unit': '台',
        'price': 8999.0,
        'stock': 50,
        'material': '金属',
        'brand': '华为',
        'color': '银色',
        'status': '正常',
        'created_at': '2025-10-20 11:00:00'
    }
]

customers_data = [
    {
        'id': 1,
        'customerCode': 'C001',
        'customerName': '张三公司',
        'customerType': '企业客户',
        'contactPerson': '张三',
        'phone': '13800138000',
        'email': 'zhangsan@example.com',
        'address': '北京市朝阳区',
        'status': '正常',
        'created_at': '2025-10-20 10:00:00'
    },
    {
        'id': 2,
        'customerCode': 'C002',
        'customerName': '李四商店',
        'customerType': '个人客户',
        'contactPerson': '李四',
        'phone': '13912345678',
        'email': 'lisi@example.com',
        'address': '上海市浦东新区',
        'status': '正常',
        'created_at': '2025-10-20 10:15:00'
    }
]

# ==================== 客户管理 ====================

@business_bp.route('/customers', methods=['GET'])
def get_customers():
    """获取客户列表"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        size = request.args.get('size', 10, type=int)
        customer_code = request.args.get('customerCode', '')
        customer_name = request.args.get('customerName', '')
        customer_type = request.args.get('customerType', '')
        
        # 模拟客户数据
        customers = [
            {
                'id': 1,
                'customerCode': 'C001',
                'customerName': '张三公司',
                'customerType': '企业客户',
                'contactPerson': '张三',
                'phone': '13800138001',
                'email': 'zhangsan@example.com',
                'address': '北京市朝阳区',
                'status': '正常',
                'created_at': '2025-10-20 10:00:00'
            },
            {
                'id': 2,
                'customerCode': 'C002',
                'customerName': '李四贸易',
                'customerType': '个人客户',
                'contactPerson': '李四',
                'phone': '13800138002',
                'email': 'lisi@example.com',
                'address': '上海市浦东区',
                'status': '正常',
                'created_at': '2025-10-20 11:00:00'
            }
        ]
        
        # 简单的过滤逻辑
        filtered_customers = customers
        if customer_code:
            filtered_customers = [c for c in filtered_customers if customer_code.lower() in c['customerCode'].lower()]
        if customer_name:
            filtered_customers = [c for c in filtered_customers if customer_name.lower() in c['customerName'].lower()]
        if customer_type:
            filtered_customers = [c for c in filtered_customers if customer_type in c['customerType']]
        
        # 分页
        total = len(filtered_customers)
        start = (page - 1) * size
        end = start + size
        paginated_customers = filtered_customers[start:end]
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'list': paginated_customers,
                'total': total,
                'page': page,
                'size': size
            }
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@business_bp.route('/customers', methods=['POST'])
def create_customer():
    """创建客户"""
    try:
        data = request.get_json()
        
        # 模拟创建客户
        new_customer = {
            'id': 999,  # 模拟新ID
            'customerCode': data.get('customerCode', ''),
            'customerName': data.get('customerName', ''),
            'customerType': data.get('customerType', ''),
            'contactPerson': data.get('contactPerson', ''),
            'phone': data.get('phone', ''),
            'email': data.get('email', ''),
            'address': data.get('address', ''),
            'status': '正常',
            'created_at': '2025-10-20 12:00:00'
        }
        
        return jsonify({
            'code': 200,
            'message': '创建成功',
            'data': new_customer
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'创建失败: {str(e)}'}), 500

@business_bp.route('/customers/<int:customer_id>', methods=['PUT'])
def update_customer(customer_id):
    """更新客户"""
    try:
        data = request.get_json()
        
        # 模拟更新客户
        updated_customer = {
            'id': customer_id,
            'customerCode': data.get('customerCode', ''),
            'customerName': data.get('customerName', ''),
            'customerType': data.get('customerType', ''),
            'contactPerson': data.get('contactPerson', ''),
            'phone': data.get('phone', ''),
            'email': data.get('email', ''),
            'address': data.get('address', ''),
            'status': '正常',
            'created_at': '2025-10-20 12:00:00'
        }
        
        return jsonify({
            'code': 200,
            'message': '更新成功',
            'data': updated_customer
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500

@business_bp.route('/customers/<int:customer_id>', methods=['DELETE'])
def delete_customer(customer_id):
    """删除客户"""
    try:
        # 模拟删除客户
        return jsonify({
            'code': 200,
            'message': '删除成功'
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500

# ==================== 商品管理 ====================

@business_bp.route('/products', methods=['GET'])
def get_products():
    """获取商品列表"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        size = request.args.get('size', 10, type=int)
        product_number = request.args.get('productNumber', '')
        product_name = request.args.get('productName', '')
        product_model = request.args.get('productModel', '')
        
        # 使用全局数据存储
        products = products_data.copy()
        
        # 简单的过滤逻辑
        filtered_products = products
        if product_number:
            filtered_products = [p for p in filtered_products if product_number.lower() in p['productNumber'].lower()]
        if product_name:
            filtered_products = [p for p in filtered_products if product_name.lower() in p['productName'].lower()]
        if product_model:
            filtered_products = [p for p in filtered_products if product_model.lower() in p['productModel'].lower()]
        
        # 分页
        total = len(filtered_products)
        start = (page - 1) * size
        end = start + size
        paginated_products = filtered_products[start:end]
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'list': paginated_products,
                'total': total,
                'page': page,
                'size': size
            }
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@business_bp.route('/products', methods=['POST'])
def create_product():
    """创建商品"""
    try:
        data = request.get_json()
        
        # 生成新ID
        new_id = max([p['id'] for p in products_data], default=0) + 1
        
        # 创建新商品
        new_product = {
            'id': new_id,
            'productNumber': data.get('productNumber', ''),
            'productName': data.get('productName', ''),
            'productModel': data.get('productModel', ''),
            'category': data.get('productType', data.get('category', '')),
            'unit': data.get('unit', ''),
            'price': data.get('unitPrice', data.get('price', 0)),
            'stock': data.get('quantity', data.get('stock', 0)),
            'material': data.get('material', ''),
            'brand': data.get('brand', ''),
            'color': data.get('color', ''),
            'status': '正常',
            'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        # 添加到数据存储
        products_data.append(new_product)
        
        return jsonify({
            'code': 200,
            'message': '创建成功',
            'data': new_product
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'创建失败: {str(e)}'}), 500

@business_bp.route('/products/<int:product_id>', methods=['PUT'])
def update_product(product_id):
    """更新商品"""
    try:
        data = request.get_json()
        
        # 查找要更新的商品
        product_index = None
        for i, product in enumerate(products_data):
            if product['id'] == product_id:
                product_index = i
                break
        
        if product_index is None:
            return jsonify({'code': 404, 'message': '商品不存在'}), 404
        
        # 更新商品信息
        products_data[product_index].update({
            'productNumber': data.get('productNumber', products_data[product_index]['productNumber']),
            'productName': data.get('productName', products_data[product_index]['productName']),
            'productModel': data.get('productModel', products_data[product_index]['productModel']),
            'category': data.get('productType', data.get('category', products_data[product_index]['category'])),
            'unit': data.get('unit', products_data[product_index]['unit']),
            'price': data.get('unitPrice', data.get('price', products_data[product_index]['price'])),
            'stock': data.get('quantity', data.get('stock', products_data[product_index]['stock'])),
            'material': data.get('material', products_data[product_index]['material']),
            'brand': data.get('brand', products_data[product_index]['brand']),
            'color': data.get('color', products_data[product_index]['color']),
        })
        
        return jsonify({
            'code': 200,
            'message': '更新成功',
            'data': products_data[product_index]
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500

@business_bp.route('/products/<int:product_id>', methods=['DELETE'])
def delete_product(product_id):
    """删除商品"""
    try:
        # 查找要删除的商品
        product_index = None
        for i, product in enumerate(products_data):
            if product['id'] == product_id:
                product_index = i
                break
        
        if product_index is None:
            return jsonify({'code': 404, 'message': '商品不存在'}), 404
        
        # 删除商品
        deleted_product = products_data.pop(product_index)
        
        return jsonify({
            'code': 200,
            'message': '删除成功',
            'data': deleted_product
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500

# ==================== 供应商管理 ====================

@business_bp.route('/suppliers', methods=['GET'])
def get_suppliers():
    """获取供应商列表"""
    try:
        # 模拟供应商数据
        suppliers = [
            {
                'id': 1,
                'supplierCode': 'S001',
                'supplierName': '华为技术有限公司',
                'contactPerson': '王五',
                'phone': '13800138003',
                'email': 'wangwu@huawei.com',
                'address': '深圳市龙岗区',
                'status': '正常',
                'created_at': '2025-10-20 10:00:00'
            }
        ]
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'list': suppliers,
                'total': len(suppliers),
                'page': 1,
                'size': 10
            }
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

# ==================== 销售管理 ====================

@business_bp.route('/sales', methods=['GET'])
def get_sales():
    """获取销售列表"""
    try:
        # 模拟销售数据
        sales = [
            {
                'id': 1,
                'orderNumber': 'SO001',
                'customerName': '张三公司',
                'productName': '苹果手机',
                'quantity': 2,
                'price': 5999.00,
                'total': 11998.00,
                'status': '已完成',
                'created_at': '2025-10-20 10:00:00'
            }
        ]
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'list': sales,
                'total': len(sales),
                'page': 1,
                'size': 10
            }
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

# ==================== 库存管理 ====================

@business_bp.route('/inventory', methods=['GET'])
def get_inventory():
    """获取库存列表"""
    try:
        # 模拟库存数据
        inventory = [
            {
                'id': 1,
                'productName': '苹果手机',
                'productModel': 'iPhone 15',
                'stock': 100,
                'minStock': 10,
                'maxStock': 200,
                'status': '正常',
                'lastUpdated': '2025-10-20 10:00:00'
            }
        ]
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'list': inventory,
                'total': len(inventory),
                'page': 1,
                'size': 10
            }
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500
